﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Jermaine.Encrypt
{
    public class DESEncrypt : IEncrypt
    {
        private static readonly string _Key = "cma;eas!~-1?234'}/${c6a1`$#@!*&^)(";

        public string Encrypt(string text, string key) {
            try {
                var des = new DESCryptoServiceProvider();
                var textBytes = Encoding.Default.GetBytes(text);

                var md5 = new MD5CryptoServiceProvider();
                var keyBytes = md5.ComputeHash(Encoding.Default.GetBytes(key)).Take(8).ToArray();

                des.Key = keyBytes;
                des.IV = keyBytes;
                var ms = new System.IO.MemoryStream();
                var cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
                cs.Write(textBytes, 0, textBytes.Length);
                cs.FlushFinalBlock();
                var sb = new StringBuilder();
                foreach (byte b in ms.ToArray()) {
                    sb.AppendFormat("{0:X2}", b);
                }
                return sb.ToString();
            } catch {

                return string.Empty;
            }

        }

        public string Encrypt(string text) {
            return Encrypt(text, _Key);
        }

        public string Decrypt(string text, string key) {
            try {

                var des = new DESCryptoServiceProvider();
                var length = text.Length / 2;
                var textBytes = new byte[length];

                int x, i;
                for (x = 0; x < length; x++) {
                    i = Convert.ToInt32(text.Substring(x * 2, 2), 16);
                    textBytes[x] = (byte)i;
                }

                var md5 = new MD5CryptoServiceProvider();
                var keyBytes = md5.ComputeHash(Encoding.Default.GetBytes(key)).Take(8).ToArray();

                des.Key = keyBytes;
                des.IV = keyBytes;

                var ms = new System.IO.MemoryStream();
                var cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
                cs.Write(textBytes, 0, textBytes.Length);
                cs.FlushFinalBlock();
                return Encoding.Default.GetString(ms.ToArray());


            } catch {
                return string.Empty;
            }
        }

        public string Decrypt(string text) {
            return Decrypt(text, _Key);
        }
    }
}
